package com.kpmg.datalake.common.tokenmanager;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.kpmg.datalake.db.model.SysUsr;

public class TokenManager {

	private TokenManager() {}
	
	private static TokenManager manager = new TokenManager();
	
	public static TokenManager getInstance() {
		return manager;
	}
	
	private static Map<String, String> userMap = new HashMap<>();
	private static Map<String, SysUsr> mapUser = new HashMap<>();
	private static Map<String, Long> timeMap = new HashMap<>();
	/**   
	 * @Fields TIMEOUT : 过期时间20分钟
	 */ 
	private static final long TIMEOUT = 1000*60*20L;
	private static final String RES = "result";
	private static final String MSG = "msg";
	
	/**  
	 * @Title:       getToken  
	 * @Description: 获取token
	 * @param userName
	 * @param user
	 * @return
	 * @author       changpengye 
	 * @version      V1.0
	 * @date         2018年5月16日 上午8:45:31
	 * @modifier     
	 * @reason       
	 */ 
	public String getToken(String userName, SysUsr user) {
		String token = "";
		if(userMap.containsKey(userName)) {
			token = userMap.get(userName);
			long now = System.currentTimeMillis();
			if(now-timeMap.get(token)<TIMEOUT) {
				timeMap.put(token, now);
				return token;
			}else {
				mapUser.remove(token);
				timeMap.remove(token);
			}
		}
		token = UUID.randomUUID().toString().replaceAll("-", "");
		userMap.put(userName, token);
		mapUser.put(token, user);
		timeMap.put(token, System.currentTimeMillis());
		return token;
	}
	
	
	/**  
	 * @Title:       checkToken  
	 * @Description: token验证
	 * @param token
	 * @return
	 * @author       changpengye 
	 * @version      V1.0
	 * @date         2018年5月16日 上午9:41:05
	 * @modifier     
	 * @reason       
	 */ 
	public Map<String, Object> checkToken(String token) {
		Map<String, Object> result = new HashMap<>();
		if(!mapUser.containsKey(token)) {
			result.put(RES, false);
			result.put(MSG, "非法token");
			return result;
		}
		long now = System.currentTimeMillis();
		if(now-timeMap.get(token)>TIMEOUT) {
			result.put(RES, false);
			result.put(MSG, "token已过期");
			return result;
		}
//		更新token刷新时间
		timeMap.put(token, now);
		SysUsr user = mapUser.get(token);
		result.put(RES, true);
		result.put("user", user);
		return result;
	}
}
